import random, requests, re
from utils.ReadUtil import read_util
from web_server_function.ServerUtils import server_utils
from bs4 import BeautifulSoup


class CourseServer:

    def add_course(self, course_stage_name, video_class_mame, subject_category_name,
                   video_course_category_name, app_rover_user_name,
                   teacher_name):
        """
        发送请求新增课程
        """
        try:
            course_title = server_utils.generate_random_string()

            data = {
                'rsNo': '',
                'index': 1,
                'coursewareIndex': '',
                'coursewareAnswerIndex': '',
                'showType': 1,
                'courseTitle': course_title,
                'courseType': 1,
                'courseStageId': read_util.read_ini()['课程阶段'][course_stage_name],
                'courseStageName': course_stage_name,
                'videoClassId': read_util.read_ini()['年级分类'][video_class_mame],
                'videoClassName': video_class_mame,
                'sysSubjectCategoryId': read_util.read_ini()['学科分类'][video_class_mame + subject_category_name],
                'sysSubjectCategoryName': subject_category_name,
                'videoCourseCategoryId': read_util.read_ini()['课程类型'][
                    video_class_mame + subject_category_name + video_course_category_name],
                'videoCourseCategoryName': video_course_category_name,
                'courseCodeA': str(random.randint(10, 99)),
                'courseCodeB': str(random.randint(10, 99)),
                'courseCodeC': str(random.randint(10, 99)),
                'courseCodeD': str(random.randint(10, 99)),
                'sort': 3519,
                'approverUserId': read_util.read_ini()['上级审核人'][app_rover_user_name],
                'approverUserName': app_rover_user_name,
                'courseIntro': '测试',
                'tPrice': 0.01,
                'recommendatoryPrice': 0.01,
                'courseCover': 'information/sys_fac19b0b-697d-447d-bbee-40541812e383.jpg',
                'courseChapterUrl': 'information/sys_4073bad9-7083-4e3a-96fe-d825b137738f.jpg',
                'teacherId': read_util.read_ini()['讲师'][teacher_name],
                'teacherName': teacher_name,
                'videoCourseChapter[1].indexNum': 1,
                'videoCourseChapter[1].flagDel': 0,
                'videoCourseChapter[1].sort': 1,
                'videoCourseChapter[1].videoCourseTitle': '测试',
                'videoCourseChapter[1].courseCode': '001',
                'videoCourseChapter[1].courseIntro': '测试001',
                'videoCourseChapter[1].tPrice': 0.01,
                'videoCourseChapter[1].recommendatoryPrice': 0.01,
                'videoCourseChapter[1].courseCover': 'information/sys_73d1d232-d730-4ebf-a969-64a4a84dd711.jpg',
                'videoCourseChapter[1].videoDataIds': '',
                'videoCourseChapter[1].videoChatperDataList[0].videoDataId': '749617aa2f6a11eea40d043f72d8910a',
                'videoCourseChapter[1].videoChatperDataList[0].videoDataTitle': '教辅测试-3',
                'videoCourseChapter[1].videoChatperDataList[0].videoDuration': 55,
                'videoCourseChapter[1].videoChatperDataList[0].courseCode': '001',
                'videoCourseChapter[1].videoChatperDataList[0].sort': 1,
                'videoCourseChapter[1].wareAnswerVideoDataIds': '',
                '_validator_ajaxsubmit': 'true'
            }
            # 新增课程
            add_date_resp = server_utils.post_request(url="/videocourseinformation/addorupdate.html", data=data).json()
            print(add_date_resp)
            # 测试教研主管登录进行审核
            server_utils.login_background(read_util.read_data()['后台账号密码']['测试教研主管账号'],
                                          read_util.read_data()['后台账号密码']['测试教研主管密码'])
            # 根据课程标题查询课程rsNo
            resp = course_server.find_course_by_title(course_title)
            print(resp)
            rs_no = course_server.query_course_rsNo(resp)
            print(rs_no)
            # 审核课程
            response = course_server.audit_course(rs_no, '2', '审核已通过')
            if response:
                print(response)
            else:
                print("新增课程失败或响应无效。")
        except Exception as e:
            print(f"请求出现异常: {e}")

    def find_course_by_title(self, course_title):
        """
        查询课程根据课程标题查询
        """
        try:
            params = {
                "result": 1,
                "courseTitle": course_title,
                "courseType": -1,
                "courseStageId": -1,
                "videoClassId": -1,
                "sysSubjectCategoryId": -1,
                "videoCourseCategoryId": -1,
                "teacherId": ""
            }
            response = server_utils.get_request(url="/videocourseinformation/nochecklist.html", params=params).text
            if response:
                return response
            else:
                print("查询课程失败或响应无效。")
        except Exception as e:
            print(f"请求出现异常: {e}")

    def query_course_rsNo(self, course_data):
        # 使用BeautifulSoup解析HTML内容
        soup = BeautifulSoup(course_data, 'html.parser')

        # 找到所有包含onclick属性且该属性中包含'auditCheck('的按钮元素
        audit_check_buttons = soup.find_all('button', attrs={'onclick': lambda value: value and 'auditCheck(' in value})

        # 提取auditCheck函数中的值
        audit_check_values = []
        for button in audit_check_buttons:
            onclick_attr = button['onclick']
            # 假设auditCheck函数的调用格式是auditCheck('some_value')
            start_index = onclick_attr.find("'") + 1  # 找到第一个单引号的位置
            end_index = onclick_attr.find("'", start_index)  # 找到第二个单引号的位置
            audit_check_value = onclick_attr[start_index:end_index]  # 提取两个单引号之间的值
            audit_check_values.append(audit_check_value)

        return audit_check_values[0]

    @staticmethod
    def get_course_order_list(order_no):
        """根据课程订单号查询课程列表"""
        params = {
            "orderNo": order_no,
        }
        response = server_utils.get_request(url="/orderslist/list.html", params=params).text
        if response:
            return response

            # # 使用正则表达式提取值
            # pattern = r"getCourseList\('([a-f0-9]{32})'\)"
            # match = re.search(pattern, response)
            # if match:
            #     extracted_value = match.group(1)
            #     return extracted_value
            # else:
            #     print("未找到匹配的值")

    @staticmethod
    def setting_course_money(course_list, order_no):
        """
        设置课程金额
        """
        try:
            data = {
                "id": course_list,
                "orderNo": order_no,
                "seniorClass": "1",
                "seniorClassCost": "0.01",
                "classMoneyInfo": f'{{"id":"{course_list}","orderNo":"{order_no}","seniorClass":"1","seniorClassCost":"0.01","classMoneyInfo":"","approverUserId":"","approverUserName":"","remark":"","businessType":""}}'
            }
            response = server_utils.post_request(url="/orders/firstOrderClassMoneySettings.html", data=data).json()
            if response:
                return response
            else:
                print("设置课程金额失败或响应无效.")
        except Exception as e:
            print(f"请求出现异常: {e}")

    def audit_course(self, rs_no, approval_status, remark):
        """
        审核新增的课程模块, approval_status=2为审核通过 =3为审核不通过
        """
        try:
            data = {
                "rsNo": rs_no,
                "approvalStatus": approval_status,
                "remark": remark,
            }
            response = server_utils.post_request("/videoCourseInformation/updateAuditStatus.html", data).json()
            if response:
                return response
            else:
                print("审核课程失败或响应无效.")
        except Exception as e:
            print(f"请求出现异常: {e}")

    def add_course_withdrawal_Request(self, orders_id, user_info_id, orders_no):
        """
        创建课程退课申请
        """
        try:
            data = {
                'rsNo': '',
                'ordersId': orders_id,
                'userInfoId': user_info_id,
                'orderType': '',
                'sellType': '',
                'refundType': '1',
                'juniorClass': '',
                'seniorClass': '1',
                'operationType': 'add',
                'ordersNo': orders_no,
                'orderTypeStr': '正常订单',
                'sellTypeStr': '正常放课',
                'payAmount': '0.01',
                'refundMode': '1',
                'refundModeName': '系统自动退款',
                'mobilePhone': '13600000000',
                'approverUserId': 'a8f3c5c74e3111eaad8798039bc0d618',
                'approverUserName': '管理主管（测试）',
                'refundTypeName': '1',
                'refundPercent': '',
                'applyRefundAmount': '0.01',
                'originalGradeInfo': '{"seniorClassDesc":"高一","seniorClassCost":0.01,"seniorClass":1}',
                'originalGradeInfoName': '高一 0.01',
                'juniorClassCost': '0.00',
                'seniorClassCost': '0.00',
                'attachmentUrls': 'activity/sys_656873e7-a318-4a71-a4fe-9aae83fae82f.jpg',
                'remark': '测试嘿嘿嘿',
                '_validator_ajaxsubmit': 'true'
            }
            response = server_utils.post_request(url="/refundCourse/addorupdate.html", data=data).json()
            if response:
                return response
            else:
                print("创建课程退课申请失败或响应无效.")
        except Exception as e:
            print(f"请求出现异常: {e}")

    def query_course_rsNo_byname(self, course_data, name):
        # 使用BeautifulSoup解析HTML内容
        soup = BeautifulSoup(course_data, 'html.parser')

        # 找到所有包含onclick属性且该属性中包含'auditCheck('的按钮元素
        audit_check_buttons = soup.find_all('button', attrs={'onclick': lambda value: value and f'{name}(' in value})

        # 提取auditCheck函数中的值
        audit_check_values = []
        for button in audit_check_buttons:
            onclick_attr = button['onclick']
            # 假设auditCheck函数的调用格式是auditCheck('some_value')
            start_index = onclick_attr.find("'") + 1  # 找到第一个单引号的位置
            end_index = onclick_attr.find("'", start_index)  # 找到第二个单引号的位置
            audit_check_value = onclick_attr[start_index:end_index]  # 提取两个单引号之间的值
            audit_check_values.append(audit_check_value)

        return audit_check_values[0]

    def query_courseupdate_rsno(self, orderno):
        """
        查询课程订单rsno
        """
        try:
            response = server_utils.get_request(
                url=f"/refundCourse/findMine.html?ordersNo={orderno}&userName=&mobilePhone=&applyStatus=&refundType=&orderType=&sellType=").text
            if response:
                return self.query_course_rsNo_byname(response, 'toaddorupdate')
            else:
                print("查询课程订单失败或响应无效.")
        except Exception as e:
            print(f"请求出现异常: {e}")

    def refund_review_by_manager(self, rsno):
        """
        多角色主管、经理审核退课申请
        """
        # 审核退课-主管
        # 主管登录
        server_utils.login_background(read_util.read_data()['后台账号密码']['测试主管账号'],
                                      read_util.read_data()['后台账号密码']['测试主管密码'])
        supervisor_data = {
            'rsNo': rsno,
            'remark': '主管通过',
            'approverUserId': '214c997e4e3111eaad8798039bc0d618',
            'approverUserName': '平台经理（测试）'
        }
        server_utils.post_request('/refundCourse/audit.html', supervisor_data)

        # 审核退课-经理
        # 经理登录
        server_utils.login_background(read_util.read_data()['后台账号密码']['测试经理账号'],
                                      read_util.read_data()['后台账号密码']['测试经理密码'])
        manager_data = {
            'rsNo': rsno,
            'remark': '经理通过',
            'approverUserId': '559e66c11af911eaad8798039bc0d618',
            'approverUserName': '邬'
        }
        server_utils.post_request('/refundCourse/audit.html', manager_data)

        # 审核退课-总监
        # 总监登录
        server_utils.login_background(read_util.read_data()['后台账号密码']['测试总监账号'],
                                      read_util.read_data()['后台账号密码']['测试总监密码'])
        wu_data = {
            'rsNo': rsno,
            'remark': '总监通过',
            'approverUserId': ''
        }
        wu_resp = server_utils.post_request('/refundCourse/audit.html', wu_data).json()
        return wu_resp

    def finance_confirm_receipt_refund(self, orderno, courselistid):
        """
        财务审核课程退款
        """
        try:
            business_object_id = None
            data = {
                'orderNo': orderno
            }
            resp = server_utils.post_request(url='/pendingCheckRefund/list.html', data=data).text

            # 使用 BeautifulSoup 解析 HTML
            soup = BeautifulSoup(resp, 'html.parser')

            # 找到包含 onClickComfirmRefund 的 <a> 标签
            link = soup.find('a', onclick=lambda x: x and 'onClickComfirmRefund' in x)

            if link:
                # 获取 onclick 属性的值
                onclick_value = link['onclick']

                # 提取参数
                # 解析出参数部分
                params = onclick_value[onclick_value.index('(') + 1:onclick_value.index(')')].split(',')

                business_object_id = params[0].strip().strip("'")

            submitdata = {
                'businessObjectId': business_object_id,
                'orderId': courselistid,
                'dataType': '2',
                'refundMode': '1',
                'amountType': '2',
                'refundAmount': '0.01',
                'refundAmountDetault': '0.01',
                'applyTimeNumber': '1727077404000',
                'originalGradeInfo': '高一 0.01',
                'gradeInfoAfterChange': '高一 0.00'
            }

            response = server_utils.post_request(url='/pendingCheckRefund/submitConfirmRefund.html',
                                                 data=submitdata).json()
            if response:
                return response
            else:
                print("财务审核课程退款失败或响应无效.")
        except Exception as e:
            print(f"请求出现异常: {e}")

    @staticmethod
    def audit_study_methods(sql):
        server_utils.execute_sql_function(sql)

    @staticmethod
    def get_refundCourse_orders(order_no):
        """根据订单编号号查询可换课订单列表"""
        return server_utils.get_request(
            url=f"/refundCourse/orders.html?refundOrChangeType=2&orderStatus=2&orderNo={order_no}&mobile=").text

    @staticmethod
    def course_change_get_orders(orders_id):
        """获取课程变更的订单"""
        data = {
            "ordersId": orders_id,
        }
        response = server_utils.post_request("/coursechange/getOrders", data).json()
        return response

    @staticmethod
    def puchased_Course(rsNo):
        """已购买的课程"""
        response = server_utils.get_request(
            f"/orders/puchasedCourse/{rsNo}.html?courseIds=&chapterIds=&changeCourseId=&showMark=1").text
        return response

    def courseChange_addUpdate(self, orders_no, want_courses):
        """添加换课申请"""
        # 根据订单编号查询订单，并设置年级金额
        orderlist = self.get_course_order_list(orders_no)
        courselist = server_utils.get_button_value_from_response(orderlist, '学习计划', 'getCourseList')
        course_server.setting_course_money(courselist, orders_no)

        # 查询登录账号发布的订单，不包括已经退换课的
        resp = self.get_refundCourse_orders(orders_no)
        ordersld = server_utils.get_input_value_from_response(html_content=resp, class_name='js-checkbox js-check',
                                                              input_name='value')

        # 获取要更换的课程订单信息
        resp = self.course_change_get_orders(ordersld)
        ordersRSNo = resp['rsNo']
        userInfold = resp['userInfoId']

        # 要换的订单的对应课程
        hadbuyresp = self.puchased_Course(resp['rsNo'])
        courseldsresp = server_utils.get_input_value_from_response(hadbuyresp, 'js-checkbox js-check', 'value')
        courselds = courseldsresp

        # 要换的课程
        videoCourselds = read_util.read_data()['课程模块id对应'][want_courses]

        # 　添加换课申请接口请求数据
        refundData = {
            'rsNo': '',
            'ordersRsNo': ordersRSNo,
            'chapterIds': '',
            'courseIds': courselds,
            'videoCourseIds': videoCourselds,
            'videoChapterIds': '',
            'ordersJuniorClass': '3',
            'ordersSeniorClass': '',
            'ordersId': ordersld,
            'ordersNo': orders_no,
            'userInfoId': userInfold,
            'showType': '',
            'courseShowType': '',
            'mobilePhone': '13200000000',
            'disparity': '0',
            'changeType': '3',
            'differenceType': '-1',
            'priceDifference': '0.00',
            'approverUserId': read_util.read_data()['上级审核人']['临时管理主管']['id'],
            'approverUserName': read_util.read_data()['上级审核人']['临时管理主管']['姓名'],
            'originalGradeInfo': '初三 0.01',
            'juniorClass': '',
            'juniorClassCost': '0',
            'seniorClass': '3',
            'seniorClassCost': '0.01',
            'attachmentUrls': 'activity/sys_656873e7-a318-4a71-a4fe-9aae83fae82f.jpg',
            'remark': '嘿嘿',
            '_validator_ajaxsubmit': True
        }

        # 　print(refundData)　调试输出
        return server_utils.post_request(url='/courseChange/addOrUpdateV2.html', data=refundData).json()

    @staticmethod
    def checkPendingListV2(order_no):
        """根据订单编号查询换课管理--待审核列表"""
        params = {
            "ordersNo": order_no,
        }
        return server_utils.get_request(url="/courseChange/checkPendingListV2.html", params=params).text

    @staticmethod
    def courseChange_approval(button_number, approver_userid, approver_username):
        """审核换课申请"""
        data = {
            'remark': '',
            'approverUserId': approver_userid,
            'approverUserName': approver_username
        }

        return server_utils.post_request(url=f'/courseChange/approvalV2/{button_number}.html', data=data).json()

    def peopleAudit_courseChange(self, orders_no):
        # 临时管理主管审核行为
        server_utils.login_background(read_util.read_data()['后台账号密码']['测试临时管理主管账号'],
                                      read_util.read_data()['后台账号密码']['测试临时管理主管密码'])
        # 根据订单编号查询待审换课申请
        checklist = self.checkPendingListV2(orders_no)
        # print(checklist) 调试输出

        # 获取审核按钮id值
        button_number = server_utils.get_button_value_from_response(checklist, '审核', 'auditExercise')
        # print(button_number) 调试输出

        # 审核换课
        print(f"""{read_util.read_data()['上级审核人']['临时管理主管']['姓名']}开始审核""")
        print(self.courseChange_approval(button_number, read_util.read_data()['上级审核人']['姜德霄']['id'],
                                         read_util.read_data()['上级审核人']['姜德霄']['姓名']))

        # 姜德霄审核行为
        server_utils.login_background(read_util.read_data()['后台账号密码']['姜德霄账号'],
                                      read_util.read_data()['后台账号密码']['姜德霄密码'])
        print(f"""{read_util.read_data()['上级审核人']['姜德霄']['姓名']}开始审核""")
        print(self.courseChange_approval(button_number, read_util.read_data()['上级审核人']['邬']['id'],
                                         read_util.read_data()['上级审核人']['邬']['姓名']))

        # 　邬审核行为
        server_utils.login_background(read_util.read_data()['后台账号密码']['邬账号'],
                                      read_util.read_data()['后台账号密码']['邬密码'])
        print(f"""{read_util.read_data()['上级审核人']['邬']['姓名']}开始审核""")
        print(self.courseChange_approval(button_number, None, None))


course_server = CourseServer()
